package ru.niir.goodfil.ui.utils.excel;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import ru.niir.goodfil.db.Good;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class StorageEnteranceExport {

    public static void storageEnteranceListToExcel(List<Good> goods) throws IOException {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet("0");
        int j = 0;
        int i = 0;
        HSSFRow header = sheet.createRow(i);
        Cell code = header.createCell(j);
        code.setCellValue("Код товара");
        sheet.autoSizeColumn(j);
        j++;

        Cell c1count = header.createCell(j);
        c1count.setCellValue("Остатки 1С");
        sheet.autoSizeColumn(j);
        j++;

        Cell storageCount = header.createCell(j);
        storageCount.setCellValue("Остатки на складе");
        sheet.autoSizeColumn(j);
        j++;

        Cell overflow = header.createCell(j);
        overflow.setCellValue("Излишки");
        sheet.autoSizeColumn(j);
        j++;

        Cell shortage = header.createCell(j);
        shortage.setCellValue("Недостатки");
        sheet.autoSizeColumn(j);
        j++;

        for(Good good : goods){
            j = 0;
            i++;
            HSSFRow row = sheet.createRow(i);

            Cell _code = row.createCell(j);
            _code.setCellValue(good.getCode());
            j++;

            Cell _c1count = row.createCell(j);
            _c1count.setCellValue(good.getCount());
            j++;

            Cell _storageCount = row.createCell(j);
            _storageCount.setCellValue(good.getStorageCount());
            j++;

            Cell _overflow = row.createCell(j);
            _overflow.setCellValue(good.getStorageCount() > good.getCount() ? good.getGoodCountDifference() : 0);
            j++;

            Cell _shortage = row.createCell(j);
            _shortage.setCellValue(good.getStorageCount() < good.getCount() ? good.getGoodCountDifference() : 0);
        }

            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=\"ostatki_sklada.xls\"");
            // Запись
            hssfWorkbook.write(response.getOutputStream());
            // Закрытие потока
            facesContext.responseComplete();
    }
}
